﻿/*******************************************************************
Copyright (c) 2011 이재범

*  Permission is hereby granted, free of charge, to any person
*  obtaining a copy of this software and associated documentation
*  files (the "Software"), to deal in the Software without
*  restriction, including without limitation the rights to use,
*  copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the
*  Software is furnished to do so, subject to the following
*  conditions:
* 
*  The above copyright notice and this permission notice shall be
*  included in all copies or substantial portions of the Software.
* 
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
*  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
*  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
*  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
*  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*  OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************/


#include "server.h"
#include <zmq.h>
#include "search.h"
#pragma comment(lib, "libzmq.lib")
Server::Server()
{
	context = zmq_init (1);

	// Python Client 와 연결하기 위해 responder 를 생성한다.
	responder = zmq_socket (context, ZMQ_REP);
	zmq_bind (responder, "tcp://*:5555");

	cout << endl << "SERVER STARTED! " << endl;

	// 클라이언트로 부터 입력을 기다린다. 
	zmq_msg_t query;
	zmq_msg_init (&query);
	zmq_recv (responder, &query, 0); // client 로 부터 query 를 받는다. 

	char* str_query = new char [query.vsm_size + 1];
	memcpy(str_query, query.vsm_data, query.vsm_size);
	str_query[query.vsm_size] = NULL;
	cout << str_query << endl;

	std::string squery(str_query);

	Search* search = new Search(squery);
	std::vector<std::string>& search_result = search->search_result;

	send_message(convert_num_to_string(search_result.size())); // 일단 전체 검색 결과 개수를 보낸다. 

	for (int i = 0; i < search_result.size(); i++)
	{
		// 항상 주고-받기 가 이루어져야만 한다. 
		zmq_msg_t call_back;
		zmq_msg_init (&call_back);
		zmq_recv (responder, &call_back, 0);
		zmq_msg_close (&call_back);

		send_message(search_result[i]); // 검색 결과를 문자열로 쭉 전송한다. 
	}

	// 메모리의 해제
	zmq_msg_close (&query);
	delete str_query;

}
Server::~Server()
{
	zmq_close (responder);
	zmq_term (context);
}
void Server::send_message(string s)
{
	zmq_msg_t msg;
	zmq_msg_init_size (&msg, s.size()); // 메세지를 위한 공간 할당

	memcpy(zmq_msg_data (&msg), s.c_str(), s.size());

	zmq_send(responder, &msg, 0); // 메세지 전송

	zmq_msg_close(&msg);
}